﻿using System;
using System.Collections.Generic;

public class EventMgr : Singleton<EventMgr>
{

    private Dictionary<string, List<Action<Message>>> handlerMap = null;

    protected override void initialize()
    {
        handlerMap = new Dictionary<string, List<Action<Message>>>();
    }

    public void addListener(string cmd, Action<Message> handler)
    {
        List<Action<Message>> lst;
        if (!handlerMap.TryGetValue(cmd, out lst))
        {
            lst = new List<Action<Message>>();
            handlerMap.Add(cmd, lst);
        }
        if (!lst.Contains(handler))
        {
            lst.Add(handler);
        }

    }

    public void dispatch(Message msg)
    {
        List<Action<Message>> lst;
        if (handlerMap.TryGetValue(msg.Name, out lst))
        {
            for (int i = 0; i < lst.Count; i++)
            {
                lst[i].Invoke(msg);
            }
        }
    }

    public void dispatch(string cmd, params object[] objs)
    {
        Message msg = new Message(cmd, objs);
        dispatch(msg);
    }

}

